
package com.wallj.videolibrary.filters;

import android.content.Context;
import android.opengl.GLES30;
import com.wallj.videolibrary.utils.OpenGLUtils;

/**
 * created by jw200 at 2019/4/8 10:57
 **/
public class GLPixelationFilter extends GLImageFilter {

    protected int imageWidthFactor;

    protected int imageHeightFactor;

    protected int pixel;

    protected int pixelStart;

    protected int pixelWidth;

    protected int pixelHeight;

    protected float mImageWidthFactor;

    protected float mImageHeightFactor;

    protected float mPixel = 6f;

    protected float[] mPixelStart = new float[] {
            0.01f, 0.86f
    };

    protected float mPixelWidth = 0.9f;

    protected float mPixelHeight = 0.14f;

    public GLPixelationFilter(Context context) {
        this(context, VERTEX_SHADER,
                OpenGLUtils.getShaderFromAssets(context, "shader/base/fragment_pixelation.glsl"));
    }

    public GLPixelationFilter(Context context, String vertexShader, String fragmentShader) {
        super(context, vertexShader, fragmentShader);
    }

    @Override
    public void initProgramHandle() {
        super.initProgramHandle();
        if (mProgramHandle != OpenGLUtils.GL_NOT_INIT) {
            imageWidthFactor = GLES30.glGetUniformLocation(mProgramHandle, "imageWidthFactor");
            imageHeightFactor = GLES30.glGetUniformLocation(mProgramHandle, "imageHeightFactor");
            pixel = GLES30.glGetUniformLocation(mProgramHandle, "pixel");
            pixelStart = GLES30.glGetUniformLocation(mProgramHandle, "pixelStart");
            pixelWidth = GLES30.glGetUniformLocation(mProgramHandle, "pixelWidth");
            pixelHeight = GLES30.glGetUniformLocation(mProgramHandle, "pixelHeight");
        }
    }

    @Override
    public void onInputSizeChanged(int width, int height) {
        super.onInputSizeChanged(width, height);
        if (width > 0) {
            mImageWidthFactor = 1.0f / width;
        }
        if (height > 0) {
            mImageHeightFactor = 1.0f / height;
        }
    }

    public void setPixels(float startX, float startY, float width, float height) {
        mPixelStart[0] = startX;
        mPixelStart[1] = startY;
        mPixelWidth = width;
        mPixelHeight = height;
    }

    @Override
    public void onDrawFrameBegin() {
        super.onDrawFrameBegin();
        GLES30.glUniform1f(imageWidthFactor, mImageWidthFactor);
        GLES30.glUniform1f(imageHeightFactor, mImageHeightFactor);
        GLES30.glUniform1f(pixel, mPixel);
        GLES30.glUniform2f(pixelStart, mPixelStart[0], mPixelStart[1]);
        GLES30.glUniform1f(pixelWidth, mPixelWidth);
        GLES30.glUniform1f(pixelHeight, mPixelHeight);
    }
}
